/**
 * @Copyright:Copyright (c) 2007 - 2023
 * 
 */
package com.tengtong.duang.app.query.core;

import java.util.regex.Matcher;

import com.tengtong.commons.lang.ExceptionUtils;
import com.tengtong.commons.lang.RegexUtils;
import com.tengtong.commons.lang.StringUtils;

/**
 * 单个表达式
 *
 * @author lin_jinming
 * @since: v1.0
 */
public record FieldValueExpress(
    String name,                // 字段名称
    ExpressFunc func,           // 操作符
    Object value                // 查询值
) {
    
    public FieldValueExpress(String name, ExpressFunc func, Object value) {
        //字段不能包含非法字符
        if(!RegexUtils.isKeyword(name)) {
            throw ExceptionUtils.ofRuntime("语法错误|字段名不合法：{}", name);
        }
        
        this.name = name;
        this.func = func;
        this.value = value;
    }
    
    public String getValue() {
        return StringUtils.asString(value);
    }
    
    /**
     * 静态创建方法
     *
     * @param fieldName
     * @param f
     * @param v
     * @return
     */
    public static FieldValueExpress of(String fieldName, ExpressFunc f, Object v) {
        return new FieldValueExpress(fieldName, f, v);
    }
    
    /**
     * exporess 包含 func 与参数
     *
     * @param fieldName
     * @param express
     * @return
     */
    public static FieldValueExpress of(String fieldName, Object express) {
        if(express == null) {
            throw ExceptionUtils.ofRuntime("语法错误|表达式不能为空：{}", fieldName);
        }
        if(express instanceof String sp) {
            sp = sp.trim();
            if(sp.charAt(0) == '[' && sp.charAt(sp.length()-1) == ']') {
                // btween 操作
                return of(fieldName, ExpressFunc.Between, sp.substring(1, sp.length()-1));
            } else {
            
                Matcher matcher = RegexUtils.FUNC_PATTERN.matcher(sp.trim());
                if(matcher.find() && matcher.groupCount() == 2) {
                    var funcName = matcher.group(1);
                    var funcParams = matcher.group(2);
                    
                    var op = ExpressFunc.fromValue(funcName);
                    
                    if(op != null) {
                        
                        return of(fieldName, op, funcParams);
                    } else {
                        throw ExceptionUtils.ofRuntime("语法错误|不认识的操作: {}", funcName);
                    }
                } else {
                    return of(fieldName, ExpressFunc.Eq, sp);
                }
            }
        } else {
            return of(fieldName, ExpressFunc.Eq, express);
        }
    }
    
}
